package com.nbcb.fund.common.interceptor;

import com.nbcb.fund.common.exception.exception.BusinessException;
import com.nbcb.fund.common.util.ThreadLocalUtil;
import com.nbcb.fund.entity.code.FundCode;
import com.nbcb.fund.entity.po.FundUserLoginTokenPo;
import com.nbcb.fund.entity.po.FundUserPo;
import com.nbcb.fund.service.FundUserLoginTokenService;
import com.nbcb.fund.service.FundUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author 九分石人
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    FundUserLoginTokenService fundUserLoginTokenService;
    @Autowired
    FundUserService fundUserService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String authorization = request.getHeader("Authorization");
        String token = authorization;
        // if (null != cookies) {
        //     for (Cookie cookie : cookies) {
        //         if ("token".equals(cookie.getName())) {
        //             token = cookie.getValue();
        //         }
        //     }
        // }
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(FundCode.UN_LOGIN);
        } else {
            FundUserLoginTokenPo fundUserLoginTokenPo = fundUserLoginTokenService.getByToken(token);
            if (fundUserLoginTokenPo == null) {
                throw new BusinessException(FundCode.UN_LOGIN);
            } else {
                FundUserPo fundUserPo = fundUserService.getByUserId(fundUserLoginTokenPo.getUserId());
                ThreadLocalUtil.set(fundUserPo);
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}